/**
 * 打开窗口
 * @param option
 * --url 窗口打开地址
 * --title 窗口标题
 * --width 窗口宽度
 * --height 窗口高度
 * --formName 子页面要提交的form表单的名称
 * --beforeSubmitFunName 子页面form表单提交前操作
 * --validationName 子页面验证方法名称
 * --submitUrl 子页面form表单提交的地址
 * --success 提交成功后处理函数
 */
function openWindow(option){
	  if(option){
		  option.title=option.title!=null?option.title:'新增窗口';
		  option.width=option.width!=null?option.width:'700px';
		  option.height=option.height!=null?option.height:'600px';
	  }
	  if(!option.url)
		  return;
	  layer.open({
		  type: 2,
		  title:option.title,
		  area: [option.width, option.height],
		  fix: false,
		  maxmin: true,
		  content: option.url,
		  btn: ['保存', '关闭'],
		  btn1: function(index, layero){
			  if(!option.submitUrl||!option.formName)
				  return;
			  var _iframe = $(layero).find("#layui-layer-iframe"+index)[0].contentWindow;
          	  if(option.beforeSubmitFunName)
          		_iframe.eval(option.beforeSubmitFunName)();
			  var options = {
                //target: '#output',          //把服务器返回的内容放入id为output的元素中
                beforeSubmit:function showRequest(formData, jqForm, options){
                	var v = null
                	if(option.validationName)
                	    v = _iframe.eval(option.validationName);
                	else
                	    v = _iframe.validatorForm;
                	if(v!=null)
	                	return v.validate();  //只要不返回false，表单都会提交,在这里可以对表单元素进行验证
                	else
                		return true;
	            },  //提交前的回调函数
                success: function(data, status){//表单初始化
                	console.dir(data);
                	layer.close(index);
                	if(option.success!=null)
						  option.success();
	            },      //提交后的回调函数
	            error: function(data, status){
	            }, 
                url: option.submitUrl,                 //默认是form的action， 如果申明，则会覆盖
                type: 'post',               //默认是form的method（get or post），如果申明，则会覆盖
                dataType: 'json',           //html(默认), xml, script, json...接受服务端返回的类型
                //clearForm: true,          //成功提交后，清除所有表单元素的值
                //resetForm: true,          //成功提交后，重置所有表单元素的值
                timeout: 30000               //限制请求的时间，当请求大于3秒后，跳出请求
              }
			  $(layero).find("#layui-layer-iframe"+index).contents().find("#"+option.formName).ajaxSubmit(options);
		  },
		  btn2: function(index, layero){
			  layer.close(index);
		  }
		});
  }


/**
 * 删除确认
 * @param option
 * --url 删除数据的地址
 * --data 删除的json数据
 * --success 提交成功后处理函数
 */
function toDelete(option){
	option.confirmMsg="是否需删除该项？";
	option.showMsg="该数据已经成功删除";
	toConfirm(option);
}

/**
 * 删除确认
 * @param option
 * --url 删除数据的地址
 * --data 删除的json数据
 * --success 提交成功后处理函数
 * --confirmMsg 确认提醒信息
 * --showMsg 操作后显示信息
 */
function toConfirm(option){
	if(option==null)
		layer.msg('没有配置地址和数据', {icon: 2});
	if(option.url==null)
		layer.msg('没有配置url地址', {icon: 2});
	if(option.data==null)
		layer.msg('没有要删除的data数据', {icon: 2});
	if(option.confirmMsg==null)
		option.confirmMsg="确认操作？";
	if(option.showMsg==null)
		option.showMsg="操作成功!";
	layer.confirm(option.confirmMsg, {
		  btn: ['确认','取消'] //按钮
	  }, function(index){
		  $.ajax({
			  type: 'POST',
			  url: option.url,
			  data: option.data,
			  dataType: 'json',
			  success:function(data){
				  if(data.ok){
					  layer.msg(option.showMsg, {icon: 1});
					  if(option.success!=null)
						  option.success();
				  }
			  }
			});
	  }, function(){
		  
	  });
}

/**
 * 验证表单信息
 * @param formIdOrName
 * @returns {Validator}
 */
function validator(formIdOrName){
	return new Validator(formIdOrName, {
	    fields: {},
	    // 参数：errorEl 错误信息节点，fieldEl 出现错误的表单节点
	    errorPlacement: function(errorEl, fieldEl) {
	        // 错误位置
	        if (fieldEl.parentNode !== undefined) {
		        fieldEl.parentNode.appendChild(errorEl);
		    }
	    },
	    callback: function(event, errors) {
	        // 阻止表单提交
	        // 回调函数
	    }
	});
}



/**
 * 树控件
 */
$(document).ready(function(){
	
	/**
	 * 树控件
	 * 属性：data-tree-id/input主键
	 * 属性：data-tree-name/input name
	 * 属性：data-tree-class/input 样式
	 * 属性：data-tree-url/树地址
	 * 属性：data-tree-onClick/树点击事件
	 * 属性：data-tree-checktype/树类型，默认不启用,radio,check
	 */
	$(".simple-tree").each(function(index,element){
		var treeid = $(element).attr("data-tree-id");
		var treename = $(element).attr("data-tree-name");
		var treeclass = $(element).attr("data-tree-class");
		var _url = $(element).attr("data-tree-url");
		var checktype = $(element).attr("data-tree-checktype");
		var _onClick = $(element).attr("data-tree-onClick");
		var _onCheck = $(element).attr("data-tree-onCheck");
		var setting = {
			data: {
				simpleData: {
					enable: true
				}
			}
			,check: {
				enable: false
			}
			,async: {
				enable: true,
				url:_url
			}
			,callback: {
				onClick: eval(_onClick),
				onCheck: eval(_onCheck)
			}
		};
		
		if("radio"==checktype){
			setting.check.chkStyle="radio";
			setting.check.radioType="all";
			setting.check.enable=true;
		}else if(checktype){
			setting.check.enable=true;
		}
		/**
		 * 获取随机guid
		 * @returns
		 */
		function guid() {
		    function S4() {
		        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		     }
		     return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
		}
		if(!treeid)
			treeid = "tree_"+guid();
		if(!treename)
			treename = treeid;
		$(element).html('<ul id="'+treeid+'" name="'+treename+'" class="ztree '+treeclass+'"></ul>')
		$.fn.zTree.init($('#'+treeid), setting);
	});
	
	/**
	 * 下拉单选、多选树控件
	 * 属性：data-tree-id/input主键
	 * 属性：data-tree-name/input name
	 * 属性：data-tree-value/input value
	 * 属性：data-tree-class/input 样式
	 * 属性：data-tree-url/树地址
	 * 属性：data-tree-checktype/树类型，默认为单选树
	 */
	$(".drop-select-tree").each(function(index,element){
		var droptreeid = $(element).attr("data-tree-id");
		var droptreename = $(element).attr("data-tree-name");
		var droptreeclass = $(element).attr("data-tree-class");
		var droptreevalue = $(element).attr("data-tree-value");
		var _url = $(element).attr("data-tree-url");
		var checktype = $(element).attr("data-tree-checktype");
		/**
		 * 获取随机guid
		 * @returns
		 */
		function guid() {
		    function S4() {
		        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		     }
		     return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
		}
		
		if(!droptreename)
			droptreename = droptreeid;
		var guid = guid();
		
		var setting = {
				check: {
					enable: true
				},
				async: {
					enable: true,
					autoParam:["id"],
					url:_url
				},
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onAsyncSuccess:zTreeOnAsyncSuccess,
					onClick: onClick,
					onCheck: onCheck
				}
			};
		
			if(!checktype||"radio"==checktype){
				setting.check.chkStyle="radio";
				setting.check.radioType="all";
			}
			
			function onClick(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("tree_"+guid);
				zTree.checkNode(treeNode, !treeNode.checked, null, true);
				return false;
			}

			function onCheck(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("tree_"+guid),
				nodes = zTree.getCheckedNodes(true);
				var key = "";
				var val = "";
				for (var i=0, l=nodes.length; i<l; i++) {
					key += nodes[i].name + ",";
				}
				for (var i=0, l=nodes.length; i<l; i++) {
					val += nodes[i].id + ",";
				}
				if (key.length > 0 ) key = key.substring(0, key.length-1);
				if (val.length > 0 ) val = val.substring(0, val.length-1);
				var keyshow = $("#show_"+guid);
				keyshow.val(key);
				var valhidden = $("#"+droptreeid);
				valhidden.val(val);
				hideMenu();
			}

			function showMenu() {
				var inputObj = $("#show_"+guid);
				var inputOffset = $("#show_"+guid).position();
				$("#menu_"+guid).css({left:inputOffset.left + "px", top:inputOffset.top + inputObj.outerHeight() + "px"}).slideDown("fast");

				$("body").bind("mousedown", onBodyDown);
			}
			function hideMenu() {
				$("#menu_"+guid).fadeOut("fast");
				$("body").unbind("mousedown", onBodyDown);
			}
			function onBodyDown(event) {
				if (!(event.target.id == "menuBtn" || event.target.id == "show_"+guid || event.target.id == "menu_"+guid || $(event.target).parents("#menu_"+guid).length>0)) {
					hideMenu();
				}
			}
		
			$(element).html('<input id="show_'+guid+'" name="show_'+guid+'" class="'+droptreeclass+'" type="text" readonly value=""   />'
					+'<input id="'+droptreeid+'" name="'+droptreename+'" type="hidden"/>'
				+'<div id="menu_'+guid+'" style="display:none; position: absolute;z-index:1">'
				+'<ul id="tree_'+guid+'" class="ztree" style="margin-top:0; width:180px; height: 200px;"></ul>'
			+'</div>');
			$.fn.zTree.init($("#tree_"+guid), setting);
			$("ul.ztree").css({"margin-top": "0px",
				"border": "1px solid #617775",
				"background": "#f0f6e4",
				"width":"220px",
				"height":"360px",
				"overflow-y":"scroll",
				"overflow-x":"auto"});
			
			
			
			function zTreeOnAsyncSuccess(event, treeId, treeNode, msg){
				if(droptreevalue){
					var vals = droptreevalue.split(",");
					var key = "";
					for(var i=0;i<vals.length;i++){
						var zTree =   $.fn.zTree.getZTreeObj("tree_"+guid)
						var node = zTree.getNodeByParam("id", vals[i],null);
						zTree.checkNode(node, !node.checked, null, true);
						key += node.name + ",";
					}
					if (key.length > 0 ) key = key.substring(0, key.length-1);
					var keyshow = $("#show_"+guid);
					keyshow.val(key);
					var valhidden = $("#"+droptreeid);
					valhidden.val(droptreevalue);
				}
			}
			
			$("#show_"+guid).click(function(){
				showMenu();
			});
	});
	
	/**
	 * 下拉image选择控件
	 * 属性：data-image-id/input主键
	 * 属性：data-image-value/input value
	 * 属性：data-image-name/input name
	 */
	$(".drop-select-image").each(function(index,element){
		
		var _hiddenId = $(element).attr("data-image-id");
		var _hiddenName= $(element).attr("data-image-name");
		var _imageValue= $(element).attr("data-image-value");
		
		/**
		 * 获取随机guid
		 * @returns
		 */
		function guid() {
		    function S4() {
		        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		     }
		     return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
		}
		
     	var guid = guid();
     	var _menuId = 'menu_'+guid;
     	var _showId = 'show_'+guid;
     	var _menuBtn = 'menuBtn_'+guid;
     	var icons = ['fa-rub','fa-pagelines','fa-stack-exchange','fa-arrow-circle-o-right','fa-arrow-circle-o-left',
     	       	     'fa-caret-square-o-left','fa-toggle-left','fa-dot-circle-o','fa-wheelchair','fa-vimeo-square',
     	       	     'fa-try','fa-turkish-lira','fa-adjust','fa-anchor','fa-archive',
     	       	     'fa-asterisk','fa-ban','fa-bar-chart-o','fa-barcode','fa-beer',
     	       	     'fa-bell','fa-bell-o','fa-bolt','fa-book','fa-bookmark',
     	       	     'fa-bookmark-o','fa-briefcase','fa-bug','fa-building','fa-bullhorn',
     	       	     'fa-bullseye','fa-calendar','fa-calendar-o','fa-camera','fa-camera-retro',
     	       	     'fa-caret-square-o-down','fa-caret-square-o-left','fa-caret-square-o-right','fa-caret-square-o-up','fa-certificate',
     	       	     'fa-check','fa-check-circle','fa-check-circle-o','fa-check-square','fa-check-square-o',
     	       	     'fa-circle','fa-circle-o','fa-clock-o','fa-cloud','fa-cloud-download',
     	       	     'fa-cloud-upload','fa-code','fa-code-fork','fa-coffee','fa-cog',
     	       	     'fa-cogs','fa-comment','fa-comment-o','fa-comments','fa-comments-o',
     	       	     'fa-compass','fa-credit-card','fa-crop','fa-crosshairs','fa-cutlery',
     	       	     'fa-dashboard','fa-desktop','fa-dot-circle-o','fa-download','fa-edit',
     	       	     'fa-flag','fa-gamepad','fa-envelope','fa-envelope-o','fa-eraser',
     	       	     'fa-exclamation','fa-exclamation-circle','fa-exclamation-triangle','fa-eye','fa-female',
     	       	     'fa-fighter-jet','fa-film','fa-filter','fa-fire','fa-fire-extinguisher',
     	       	     'fa-gavel','fa-gear','fa-gears','fa-gift','fa-globe','fa-group',
     	       	     'fa-hdd','fa-headphones','fa-heart','fa-home','fa-inbox','fa-info-circle',
     	       	     'fa-key','fa-keyboard-o','fa-laptop','fa-leaf','fa-lemon-o','fa-level-down',
	     	       	 'fa-level-up','fa-lightbulb-o','fa-lock','fa-magic','fa-magnet','fa-male',
	 	       	     'fa-map-marker','fa-meh-o','fa-microphone','fa-microphone-slash','fa-minus','fa-minus-circle',
	 	       	     'fa-minus-square','fa-minus-square-o','fa-mobile','fa-mobile-phone','fa-money','fa-moon-o',
	 	       	     'fa-music','fa-pencil','fa-pencil-square','fa-pencil-square-o','fa-phone',
	 	       	     'fa-phone-square','fa-picture-o','fa-plane','fa-plus','fa-plus-circle',
	 	       	     'fa-plus-square','fa-power-off','fa-print','fa-puzzle-piece'
     	       	       ];
     	if(!_imageValue)
     		_imageValue="fa fa-home";
     	$(element).html('<input type="hidden" name="'+_hiddenName+'" id="'+_hiddenId+'" value="'+_imageValue+'"><i id="'+_showId+'" class="'+_imageValue+'"/>'
         +'<button id="'+_menuBtn+'" type="button" style="margin-left:30px">'
         	+'<i class="fa fa-plus-square"></i>'
         +'</button>');
     	var pic = '<div id="'+_menuId+'" style="display:none; position: absolute;border: 1px solid #617775;z-index:1051;background: #f0f6e4;width:215px;height:180px;overflow-y:auto;overflow-x:auto;"><table>';
     	$.each(icons,function(i,item){
     		if(i%15==0)
     			pic+='<tr>';
     		pic+='<td> <i class="fa '+item+'"/></td>';
     		if(i%15==14)
     			pic+='</tr>';
     	});
     	pic+='</table></div>';
     	$("body").append(pic);
     	
     	this.hid=_hiddenId;
     	this.sid=_showId;
     	this.set = function(hid,sid,pic){
     		if(pic!=null&&pic!=""){
     			$('#'+hid).val(pic);
         		$("#"+sid).attr("class", pic);
     		}else{
     			$('#'+hid).val("");
         		$("#"+sid).attr("class", "icon-th");
     		}
     	}
     	
     	$("#"+_menuId).find("i").hover(function(){
     		$(this).css("color","#f34541");
     		},function(){
     		$(this).css("color","black");
     	});
     	
     	$("#"+_menuId).find("i").click(function(){
     		var color = $(this).attr("class");
     		$("#"+_showId).attr("class", color);
     		$("#"+_hiddenId).val(color);
     		hide();
     	});
     	
     	function hide() {
 			$("#"+_menuId).fadeOut("fast");
 			$("body").unbind("mousedown", onBodyDown);
 		}
     	
     	var show=function (){
     		var _input = $('#'+_showId);
     		var _offset = $('#'+_showId).offset();
 			$("#"+_menuId).css({left:_offset.left+"px", top:_offset.top + _input.outerHeight()+"px"}).slideDown("fast");
 			$("body").bind("mousedown", onBodyDown);
 		}
     	
     	var onBodyDown = function (event) {
 			if (!(event.target.id == _menuBtn || $(event.target).parents("#"+_menuBtn).length>0 ||event.target.id == _menuId || $(event.target).parents("#"+_menuId).length>0)) {
 				hide();
 			}
 		}
     	
     	$('#'+_showId).click(function(){
				show();
			});
     	
     	$('#'+_menuBtn).click(function(){
				show();
			});
     });
});
